<template>
  <el-upload
    v-model:file-list="fileList"
    drag
    multiple
    :limit="1"
    :auto-upload="false"
    :before-upload="beforeUpload"
    list-type="picture"
    :on-remove="handleRemove"
  >
    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
    <div class="el-upload__text">拖拽 或<em>点击上传</em></div>
    <template #tip>
      <div class="el-upload__tip">
        上传excel文件，请勿超过5M，每次最多只能上传1个文件
      </div>
    </template>
    <!-- 自定义缩略图 -->
    <template #file="{ file }">
      <div class="custom-thumbnail-container">
        <div class="custom-thumbnail">
          <img :src="getCustomThumbnail(file)" alt="缩略图" />
          <span>{{ file.name }}</span>
        </div>
        <el-button
          type="danger"
          size="small"
          @click.stop="handleCustomRemove(file)"
        >
          删除
        </el-button>
      </div>
    </template>
  </el-upload>
</template>

<script setup lang="ts">
import excelIcon from "@/assets/images/excel-icon.jpg";
import type { UploadProps, UploadUserFile } from "element-plus";
const fileList = defineModel<UploadUserFile[]>("file-list", {
  type: Array,
  required: true,
  default: [],
});
const beforeUpload: UploadProps["beforeUpload"] = (rawFile) => {
  console.log(rawFile);
  return true;
};

// 自定义缩略图逻辑
const getCustomThumbnail = (file: UploadUserFile) => {
  // 这里可以根据文件类型返回不同的图片
  if (file.name.endsWith(".xlsx") || file.name.endsWith(".xls")) {
    return excelIcon; // 替换为实际的 Excel 图标路径
  }
  return file.url; // 默认缩略图
};

const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

// 自定义删除逻辑
const handleCustomRemove = (file: UploadUserFile) => {
  const index = fileList.value.findIndex((f) => f.uid === file.uid);
  if (index !== -1) {
    fileList.value.splice(index, 1); // 从 fileList 中移除文件
  }
};
</script>

<style lang="scss" scoped>
.custom-thumbnail-container {
  //   padding: 8px;
  width: 100%;
  .custom-thumbnail {
    display: flex;
    align-items: center;

    border: 1px solid #ebeef5;
    border-radius: 4px;

    img {
      width: 40px;
      height: 40px;
      margin-right: 8px;
    }

    span {
      font-size: 14px;
      margin-right: 8px;
    }
  }
  .el-button {
    margin-left: auto;
  }
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
